package com.example.android2019.note;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class NoteSQliteHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;

    public NoteSQliteHelper(Context context) {
        super(context, "note.db", null, 1);
        /*初始化*/
        db = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table note(id integer primary key autoincrement,content text,time text)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public String getTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        return simpleDateFormat.format(date);
    }

    public boolean insertDate(String content, String time) {
        /*String sql = "insert into note(content,time) values(?,?)";
        db.execSQL(sql);
        return true;*/
        ContentValues cv = new ContentValues();
        cv.put("content", content);
        cv.put("time", time);
        return db.insert("note", null, cv) > 0;
    }

    public boolean deleteDate(int id) {
        return db.delete("note", "id=?", new String[]{id + ""}) > 0;
    }

    public boolean updateDate(int id, String content, String time) {
        ContentValues cv = new ContentValues();
        cv.put("content", content);
        cv.put("time", time);
        return db.update("note", cv, "id=?", new String[]{id + ""}) > 0;
    }

    public ArrayList<NoteBean> query(){
        ArrayList<NoteBean> list = new ArrayList<NoteBean>();
        String sql = "select * from note order by time desc";
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            int id = cursor.getColumnIndex("id");
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String time = cursor.getString(cursor.getColumnIndex("time"));

            NoteBean noteBean = new NoteBean(id, content, time);
            list.add(noteBean);
        }
        cursor.close();
        return list;
    }
}
